import Taro from "@tarojs/taro";
import { computed, ref } from "vue";
import {
  ResponseCodeEnum,
  ACCESS_TOKEN_CODE,
  COMMUNITY_CODE_KEY,
} from "@/constants/index";
import { apiLoginout, apiMpLogin, apiQueryUser } from "@/apis/login";
import { useUserInfo } from "./useUserInfo";

const communityCode = ref<string>(
  Taro.getStorageSync(COMMUNITY_CODE_KEY) || ""
);
const accessToken = ref<string>(Taro.getStorageSync(ACCESS_TOKEN_CODE) || "");
const wxCode = ref<string | null>(null);

export const useLogin = () => {
  const { setUserInfo } = useUserInfo();

  const isLogin = computed(() => {
    return !!accessToken.value;
  });

  const setToken = (token: string) => {
    if (!token) return;
    accessToken.value = token;
    Taro.setStorageSync(ACCESS_TOKEN_CODE, token);
  };

  const setConmunityCode = (code: string) => {
    communityCode.value = code;
    Taro.setStorageSync(COMMUNITY_CODE_KEY, code);
  };

  const login = () => {
    Taro.showLoading({ title: "登录中" });
    Taro.login({
      success: async (res: any) => {
        try {
          const { code } = res;
          wxCode.value = code;
          const loginRes: any = await apiMpLogin(code);
          if (loginRes.code !== ResponseCodeEnum.SUCCESS) {
            Taro.hideLoading();
            Taro.showToast({ title: loginRes.message, icon: "error" });
            return;
          }

          setToken(loginRes.data);

          const userRes: any = await apiQueryUser();
          if (userRes.code !== ResponseCodeEnum.SUCCESS) {
            Taro.hideLoading();
            Taro.showToast({ title: userRes.message, icon: "error" });
            return;
          }
          setUserInfo(userRes.data);

          Taro.showToast({ title: "登录成功", icon: "success" });
          // 回退
          setTimeout(() => {
            Taro.navigateBack({ delta: 1 });
          }, 200);
        } catch (error) {
          // console.error(error);
          Taro.hideLoading();
          Taro.showToast({ title: error, icon: "error" });
        }
      },
      fail: (res: TaroGeneral.CallbackResult) => {
        console.log("fail", res);
        Taro.hideLoading();
      },
    });
  };

  const loginout = () => {
    Taro.showLoading({ title: "登出中" });
    apiLoginout()
      .then((res: any) => {
        if (res.code === ResponseCodeEnum.SUCCESS) {
          accessToken.value = "";
          setToken(accessToken.value);
          setUserInfo(null);
        }
      })
      .finally(() => {
        Taro.hideLoading();
      });
  };

  return {
    isLogin,
    login,
    loginout,
    accessToken,
    setConmunityCode,
  };
};
